# _ * _ coding:utf-8 _ * _

import tornado.web
from db import db
import re, base64, hashlib
import config
import datetime, os
from pymongo import ASCENDING, DESCENDING
from random import choice
def is_ended(act):
    time = datetime.datetime.utcnow() + datetime.timedelta(hours=8)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S")
    return time_str>=act["endtime"]
    
class index(tornado.web.RequestHandler):
    def get(self):
        acts = db.activities.find(sort=[["_id", DESCENDING]])
        self.render("list.html", acts=acts, is_ended=is_ended)
        
class view(tornado.web.RequestHandler):
    def get(self, uuid):
        act = db.activities.find_one({"uuid":uuid})
        if not act:
            raise tornado.web.HTTPError(404)
        else:
            if not is_ended(act):
                db.activities.update({"uuid":uuid},{"$set":{"result":[]}})
            self.render("view.html", act=act, is_ended=is_ended)
            
class apply(tornado.web.RequestHandler):
    
    def get(self, uuid):
        act = db.activities.find_one({"uuid":uuid})
        if not act:
            raise tornado.web.HTTPError(404)
        else:
            if is_ended(act):
                self.render("apply.html", act={}, error=u"报名已截止！")
            else:
                self.render("apply.html", act=act, error=None)
                
    def post(self, uuid):
        id = self.get_argument("id", "")
        if len(id)!=12:
            self.render("apply.html", act={}, error=u"学号输入错误！")
        else:
            act = db.activities.find_one({"uuid":uuid})
            if not act:
                raise tornado.web.HTTPError(404)
            else:
                if is_ended(act):
                    self.render("apply.html", act={}, error=u"报名已截止！")
                else:
                    if id in act["appliers"]:
                        self.render("apply.html", act={}, error=u"您已经报过名了！")
                    else:
                        db.activities.update({"uuid":uuid}, {"$addToSet":{"appliers":id}})
                        self.render("apply.html", act={}, error=u"报名成功！")
                        
class result(tornado.web.RequestHandler):
    
    def get(self, uuid):
        act = db.activities.find_one({"uuid":uuid})
        if not act:
            raise tornado.web.HTTPError(404)
        else:
            if is_ended(act):
                if act["result"]:
                    self.render("result.html", act=act, error=None)
                else:
                    if act["amount"]>=len(act["appliers"]):
                        act["result"] = act["appliers"]
                    else:
                        act["result"] = []
                        for i in range(act["amount"]):
                            a = choice(act["appliers"])
                            act["appliers"].remove(a)
                            act["result"].append(a)
                    act["result_time"] = (datetime.datetime.utcnow()+datetime.timedelta(hours=8)).strftime("%Y-%m-%d %H:%M:%S")
                    db_ret = db.activities.update({"uuid":uuid,"result":[]}, {"$set":{"result":act["result"], "result_time":act["result_time"]}}, safe=True)
                    if db_ret["updatedExisting"]:
                        self.render("result.html", act=act, error=None)
                    else:
                        act = db.activities.find_one({"uuid":uuid})
                        self.render("result.html", act=act, error=None)                        
            else:
                self.render("result.html", act={}, error=u"报名尚未截止！")
            
        